package com.wu.server.controller;

import com.wu.server.code.Code;
import com.wu.server.entity.Type;
import com.wu.server.service.TypeServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
public class TypeController {
    @Autowired
    Code code;
    @Autowired
    TypeServer typeServer;
    @GetMapping("type")
    public Object queryType(
            @RequestParam(value = "id",defaultValue = "") String id,
            @RequestParam(value = "typeName",defaultValue = "") String typeName,
            @RequestParam(value = "order",defaultValue = "desc") String order,
            @RequestParam(value = "sort",defaultValue = "id") String sort,
            @RequestParam(value = "summaryRange",defaultValue = "0,9999999999") String summaryRange,
            @RequestParam(value = "salesRange",defaultValue = "0,9999999999") String salesRange,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize
    ){
        return typeServer.queryType(id,typeName,summaryRange,salesRange,order,sort,pageNum,pageSize);
    }

    @PostMapping("type")
    public Object addType(@RequestBody TypeForm form){
        if(form.typeName == null || form.typeName.equals("")) return code.getMeta(Code.PARAM_ERROR,null);
        Type type = new Type();
        type.type_name = form.typeName;
        type.type_sum = form.typeSummary;
        type.type_sales = form.typeSales;
        return typeServer.addType(type);
    }
    @PutMapping("type")
    public Object updateType(@RequestBody TypeForm form){
        if(form.id == 0 || form.typeName == null || form.typeName.equals("")) return code.getMeta(Code.PARAM_ERROR,null);
        Type type = new Type();
        type.id = form.id;
        type.type_name =  form.typeName;
        type.type_sum = form.typeSummary;
        type.type_sales = form.typeSales;
        System.out.println(form);
        return typeServer.updateType(type);
    }

    @DeleteMapping("type")
    public Object deleteType(@RequestParam(value = "id") int id){
        if(id == 0) return code.getMeta(Code.PARAM_ERROR,null);
        return typeServer.deleteType(id);
    }


    private static class TypeForm{
        public int id;
        public String typeName;
        public int typeSummary;
        public int typeSales;
    }
}
